﻿namespace Blaze.Editor
{
    using System.Collections.Generic;
    using UnityEditor;
    using UnityEngine;

    /// <summary>
    /// 在工程中筛选所有使用了指定AssetBundle名称的资源，并列在窗口中。
    /// </summary>
    public class AssetBundleNameFilterWindow : EditorWindow
    {
        [MenuItem("Blaze/分析/查找资源包引用", false, BlazeEditorMenu.Priority.Panels)]
        public static void Open()
        {
            GetWindow<AssetBundleNameFilterWindow>(false, "资源包引用", true);
        }

        protected void OnGUI()
        {
            GUILayout.BeginHorizontal();
            mSearchAssetBundleName = EditorGUILayout.TextField(mSearchAssetBundleName);
            if (GUILayout.Button("Search"))
                search();
            GUILayout.EndHorizontal();

            var tip = string.Format("{0} matched.", mMatchedObjects.Count);
            mFoldoutResult = EditorGUILayout.Foldout(mFoldoutResult, tip);
            if (!mFoldoutResult)
                return;
            mScroll = GUILayout.BeginScrollView(mScroll);
            for (var i = 0; i < mMatchedObjects.Count; i++)
            {
                var match = mMatchedObjects[i];
                EditorGUILayout.ObjectField(match.name, match, typeof (GameObject), false);
            }
            GUILayout.EndScrollView();
        }

        private void search()
        {
            mMatchedObjects.Clear();
            var assetPaths = AssetDatabase.GetAssetPathsFromAssetBundle(mSearchAssetBundleName);
            for (var i = 0; i < assetPaths.Length; i++)
            {
                var importer = AssetImporter.GetAtPath(assetPaths[i]);
                if (importer == null)
                    return;
                if (importer.assetBundleName == mSearchAssetBundleName)
                    mMatchedObjects.Add(AssetDatabase.LoadMainAssetAtPath(assetPaths[i]));
            }
            EditorUtility.ClearProgressBar();
        }

        private readonly List<Object> mMatchedObjects = new List<Object>();
        private bool mFoldoutResult;
        private Vector2 mScroll;
        private string mSearchAssetBundleName = string.Empty;
    }
}